package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * "伪框架"
 * 抽取的公共的Servlet,继承自HttpServlet
 */
public class BaseServlet extends HttpServlet {

    //重写业务方法入口
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //创建BaseServlet的子类对象---获取子类的字节码文件
            Class clazz  = this.getClass();
            //System.out.println(clazz) ;
            //创建子类对象---
            Object obj = clazz.newInstance() ;
            System.out.println(obj);
            //调用子类的方法,在浏览器发送请求的时候,地址栏约定一个格式
            //http://localhost:8080/MavenProject_2211_war_exploded/模块名称?methodName=子类的方法名
            //获取到地址栏上的参数methodName
            String methodName = request.getParameter("methodName");
            //如果当前methodName是null,地址栏没有参数
            if(methodName==null){
                methodName = "index" ; //给一个方法名 index
            }
            System.out.println(methodName);
            //通过子类的字节码文件获取子类方法所在的Method类对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //调用子类方法
            method.invoke(obj,request,response) ;
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    public void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

    }
}
